﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace SGLisp 
{
    public static class Helper
    {
        public static string  DataToLispString(object data)
        {
            if (data == null)
            {
                return "nil";
            }
            switch (data.GetType().Name)
            {
                case "Hashtable":
                    string RetString = "{\r\n";
                    foreach (DictionaryEntry item in (Hashtable)data)
                    {
                        RetString += DataToLispString(item.Key) + " " + DataToLispString(item.Value)+" \r\n";
                    }
                    RetString += "}\r\n";
                    return RetString;
                case "Object[]":
                    string vectorString = "[";
                    object[] arrData = (object[])data;
                    for (int i=0;i<arrData.Length;i++)
                    {
                        vectorString+= DataToLispString(arrData[i])+" ";
                    }
                    vectorString += "]";
                    return vectorString;
                case "String":
                    string strData = (string)data;
                    if (strData.Length > 0 && strData[0] == ':')
                    {
                        return strData;
                    }
                    return "\"" + data.ToString() + "\"";
                case "Int32":
                    return data.ToString();
                case "Single":
                    int num;
                    if (int.TryParse(data.ToString(), out num))
                    {
                        return data.ToString() + ".0";
                    }
                    return data.ToString();
            }
            return "";
        }

        public static object EvalValueFromFile(string cljPath,Context context = null)
        {
            if (context == null)
            {
                context = RT.MainContext;
            }
            ASTTree tree = RT.LoadASTTree(cljPath);
            ASTNode evalNode = RT.Evaluate(tree.Roots[0], context);
            return RT.EvalNode(evalNode, context);
        }

        public static ASTNode EvalFormString(string scriptText, Context context = null)
        {
            if (context == null)
            {
                context = RT.MainContext;
            }
            ASTTree tree = ASTTree.ParseString("inline", scriptText);
            return RT.Evaluate(tree.Roots[0], context);
        }

        public static T GetMapValue<T>(Hashtable table,object keyName,T defaultValue)
        {
            if (table.ContainsKey(keyName))
            {
                return (T)table[keyName];
            }
            return defaultValue;
        }
    }
   
} 
